package com.itfreer.file.path;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 定义文件块存储接口
 */
public class BucketManage extends BasePath {

	/**
	 * 单一实例
	 */
	public static final BucketManage instance = new BucketManage();

	private BucketManage(){

	}

	/**
	 * 创建文件存储块
	 * 
	 * @param bucketName
	 */
	public void createBucket(String bucketName) {
		String path = getBasePath();
		if(path.endsWith("/")){
			path += bucketName;
		}else{
			path += "/" + bucketName;
		}
		File fileinfo = new File(path);
		if (!fileinfo.isDirectory()) {
			fileinfo.mkdirs();
		}
	}

	/**
	 * 列举Bucket
	 * 
	 * @param prefix
	 *            限定返回的bucket name必须以prefix作为前缀，可以不设定，不设定时不过滤前缀信息
	 * @param marker
	 *            设定结果从marker之后按字母排序的第一个开始返回，可以不设定，不设定时从头开始返回
	 * @param maxKeys
	 *            限定此次返回bucket的最大数，如果不设定，默认为100，max-keys取值不能大于1000
	 * @return
	 */
	public List<String> listBuckets(String prefix, String marker, Integer maxKeys) {
		if (maxKeys == null) {
			maxKeys = 100;
		}
		if (maxKeys > 1000) {
			maxKeys = 1000;
		}
		// 从目录中获取所有数据，不分页，也不分大小
		String path = getBasePath();
		File fileinfo = new File(path);
		File[] tempList = fileinfo.listFiles();
		List<String> result = new ArrayList<String>();
		for (File item : tempList) {
			if (item.isDirectory()) {
				result.add(item.getName());
				if (result.size() >= maxKeys) {
					break;
				}
			}
		}
		return result;
	}

	/**
	 * 删除文件存储块
	 * 
	 * @param bucketName
	 */
	public void deleteBucket(String bucketName) {
		String path = getBasePath();
		if(path.endsWith("/")){
			path += bucketName;
		}else{
			path += "/" + bucketName;
		}
		
		File fileinfo = new File(path);
		fileinfo.deleteOnExit();
	}

	/**
	 * 文件存储块是否存在
	 * 
	 * @param bucketName
	 */
	public boolean doesBucketExist(String bucketName) {
		String path = getBasePath();
		if(path.endsWith("/")){
			path += bucketName;
		}else{
			path += "/" + bucketName;
		}
		
		File fileinfo = new File(path);
		return fileinfo.isDirectory();
	}
}